package com.coska;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 测试单表插入
 */
public class InsertTest extends Thread {

    public static volatile int count;
    public static Connection conn = null;

    static  {
        String url = "jdbc:postgresql://localhost:5432/postgres"; //数据库连接地址
        String name = "org.postgresql.Driver";
        String user = "postgres";
        String password = "root";//密码
        try {
            Class.forName(name);
            conn = DriverManager.getConnection(url, user, password);
//            conn.setAutoCommit(false);//关闭自动提交
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void run(){
//        long begin = System.currentTimeMillis();
        String sql = "insert into conditions (time,location,temp,timet) values " +
                "(?,?,?,?)";
        PreparedStatement pst = null;
        try {
            pst = conn.prepareStatement(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
        for(int i = 0;i < 50000;i ++){

            try {

                pst.setDate(1,new java.sql.Date(new Date().getTime()));
                pst.setString(2,"武汉" + i);
                pst.setDouble(3,i/100 + 30);
                pst.setString(4,format.format(new Date()));


                pst.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if (i % 10000 == 0){//每一万条数据停顿一秒
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
        count ++;
//        long end = System.currentTimeMillis();
//        System.out.println((end-begin) + "ms");
    }
}
